package com.iecas.handler;

import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import cn.hutool.socket.nio.ChannelHandler;
import com.iecas.context.GlobalContext;
import com.iecas.context.ServerContext;
import com.iecas.enums.BizEnum;
import com.iecas.launch.Server;
import com.iecas.request.Root;
import com.iecas.response.BaseResponse;
import com.iecas.utils.OnlineManager;
import com.iecas.utils.RequestUtils;
import com.iecas.utils.SocketChannelManager;
import lombok.Data;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
@Data
public class DefaultServerChannelHandler implements ChannelHandler {

    Server server;

    @Override
    public void handle(SocketChannel socketChannel) throws Exception {
        try {
            ByteBuffer byteBuffer = ByteBuffer.allocate(4);
            int read = socketChannel.read(byteBuffer);
            if (read > 0) {
                byteBuffer.flip();
                int dataSize = byteBuffer.getInt();
                byte[] expectBytes = RequestUtils.getExpectBytes(socketChannel, dataSize);

                Root baseRequest = RequestUtils.decode(expectBytes);
                server.log(JSONUtil.toJsonStr(baseRequest));

                BizEnum bizEnum = BizEnum.getByCode(baseRequest.getCode());
                BaseHandler handler = bizEnum.getHandler();

                BaseResponse baseResponse = handler.handle(baseRequest,server,null,socketChannel);
                ByteBuffer encode = RequestUtils.encode(baseResponse);
                encode.flip();
                socketChannel.write(encode);
            }
        }catch (Exception e){
            StaticLog.error("异常:{}",e.getMessage());
//            e.printStackTrace();
            String token = SocketChannelManager.remove(socketChannel);
            socketChannel.close();
            OnlineManager.remove(token);
            ServerContext serverContext = GlobalContext.getServerContext();
            serverContext.removeTank(token);
//            throw e;
        }
    }
}
